package com.heima.user.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.utils.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;


@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto dto) {
        // 1. 入参判空
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        String password = dto.getPassword();
        String phone = dto.getPhone();

        // 2. 校验手机号和密码是否存在
        if (StringUtils.isEmpty(phone) && StringUtils.isEmpty(password)) {
            // 4. 游客登录

            // 4.1 生成token并返回
            String token = AppJwtUtil.getToken(0L);

            // user + token
            Map<String, Object> map = new HashMap<>(2);
            map.put("user", null);
            map.put("token", token);

            return ResponseResult.okResult(map);
        }

        // 3. 正常登录

        // 3.1 校验手机号是否存在
        LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApUser::getPhone, phone);
        ApUser user = apUserMapper.selectOne(wrapper);
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        // 3.2 比对密码
        String salt = user.getSalt();
        String passwordFromDb = user.getPassword();
        String passwordAfterMd5 = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if (!passwordAfterMd5.equals(passwordFromDb)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        // 3.3 生成token
        String token = AppJwtUtil.getToken(user.getId().longValue());

        // 清空敏感数据
        user.setSalt("");
        user.setPassword("");

        // user + token
        Map<String, Object> map = new HashMap<>(2);
        map.put("user", user);
        map.put("token", token);

        // 3.4 返回数据
        return ResponseResult.okResult(map);
    }
}